package com.cuotigou.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.cuotigou.config.ConfigUtils;
import com.cuotigou.config.PayConfig;
import com.cuotigou.mapper.*;
import com.cuotigou.pojo.*;
import com.cuotigou.service.KnowledgeService;
import com.cuotigou.util.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

import static com.cuotigou.config.PayConfig.ALIPAY_APPID;
import static com.cuotigou.config.PayConfig.ALIPAY_PRIVWER_KEY;
import static com.cuotigou.config.PayConfig.ALIPAY_PUBLIC_KEY;

/**
 * Created by Administrator on 2018/11/9.
 */
@Service
@Transactional
public class KnowledgeServiceImpl implements KnowledgeService {

    private static  final Logger log = LoggerFactory.getLogger(KnowledgeServiceImpl.class);

    @Autowired
    private SKnowledgeMapper sKnowledgeMapper;
    @Autowired
    private SKnowledgeLabelMapper sKnowledgeLabelMapper;
    @Autowired
    private SKnowledgePayMapper sKnowledgePayMapper;
    @Autowired
    private SKnowledgeDiscussMapper sKnowledgeDiscussMapper;
    @Autowired
    private SUserToKnowledgeMapper sUserToKnowledgeMapper;
    @Autowired
    private SGradeMapper sGradeMapper;
    @Autowired
    private SSubjectMapper sSubjectMapper;
    @Autowired
    private SApplePayProductIdMapper sApplePayProductIdMapper;

    @Override
    public ObjectResult index(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());

        Map<String,Object> map = new HashMap<>();
        map.put("gradeId",xmlBean.getId());
        if ("全部".equals(xmlBean.getSubject())){
            map.put("subject",null);
        }else {
            map.put("subject",xmlBean.getSubject());
        }
        if (StringUtil.isEmpty(xmlBean.getTitle())){
            map.put("title",xmlBean.getTitle());
        }else {
            map.put("title","%"+xmlBean.getTitle()+"%");
        }
        map.put("userId",userId);
        map.put("isCollection",xmlBean.getIsCollection());

        List<SKnowledge> sKnowledges = sKnowledgeMapper.selectKnowledgeListBySubjectMap(map);
        //分页
        Page<SKnowledge> page = new Page<>();
        page.setP(xmlBean.getP()==null? 1:Integer.parseInt(xmlBean.getP()));
        List<SKnowledge> list = page.getPageContent(sKnowledges);

        for (SKnowledge sKnowledge:list){
            //知识点标签
            List<String> strings = sKnowledgeLabelMapper.selectLabel(sKnowledge.getId());
            sKnowledge.setLabelList(strings);

            //是否收藏
            SUserToKnowledge sUserToKnowledge = new SUserToKnowledge();
            sUserToKnowledge.setKonwlegeId(Long.parseLong(sKnowledge.getId()+""));
            sUserToKnowledge.setUserId(Long.parseLong(userId));

            SUserToKnowledge select = sUserToKnowledgeMapper.select(sUserToKnowledge);
            if (select==null){
                sKnowledge.setIsCollection(0);
            }
            else {
                sKnowledge.setIsCollection(select.getIsCollection());
            }
            //预览图片
            if (!StringUtil.isEmpty(sKnowledge.getImage())){
                sKnowledge.setImage(ConfigUtils.ADMIN_URL+sKnowledge.getImage());
            }
        }
        map.clear();
        map.put("list",list);
        map.put("count",page.getPageTotal());
        map.put("total",page.getRecordTotal());
        return ObjectResult.build("1","成功",map);
    }

    @Override
    public ObjectResult knowledgeCollection(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());

        List<SKnowledge> sKnowledges = sKnowledgeMapper.selectKnowledgeListByUserId(Integer.parseInt(userId));
        //分页
        Page<SKnowledge> page = new Page<>();
        page.setP(xmlBean.getP()==null? 1:Integer.parseInt(xmlBean.getP()));
        List<SKnowledge> list = page.getPageContent(sKnowledges);

        for (SKnowledge sKnowledge:list){
            //知识点标签
            List<String> strings = sKnowledgeLabelMapper.selectLabel(sKnowledge.getId());
            sKnowledge.setLabelList(strings);

        }
        Map<String,Object> map = new HashMap<>();
        map.put("list",list);
        map.put("count",page.getPageTotal());
        return ObjectResult.build("1","成功",map);
    }

    @Override
    public ObjectResult knowledgeDetail(XMLBean xmlBean) {

        SKnowledge sKnowledge = sKnowledgeMapper.selectByPrimaryKey(Integer.parseInt(xmlBean.getId()));

        sKnowledge.setVideoUrl(ConfigUtils.ADMIN_URL+sKnowledge.getVideoUrl());
        sKnowledge.setProductId(sApplePayProductIdMapper.selectByValue(sKnowledge.getPrice()));
        //预览图片
        if (!StringUtil.isEmpty(sKnowledge.getImage())){
            sKnowledge.setImage(ConfigUtils.ADMIN_URL+sKnowledge.getImage());
        }

        if(!StringUtil.isEmpty(xmlBean.getToken())) {
            String userId = CommonUtils.decToken(xmlBean.getToken());
            //是否支付
            SKnowledgePay sKnowledgePay = new SKnowledgePay();
            sKnowledgePay.setUserId(Long.parseLong(userId));
            sKnowledgePay.setKnowledgeId(sKnowledge.getId());
            SKnowledgePay sKnowledgePay1 = sKnowledgePayMapper.selectKnowledgePay(sKnowledgePay);

            if (sKnowledgePay1 == null) {
                sKnowledge.setIsPay(0);
            } else {
                sKnowledge.setIsPay(sKnowledgePay1.getIsPay());
            }

            //是否收藏
            SUserToKnowledge sUserToKnowledge = new SUserToKnowledge();
            sUserToKnowledge.setKonwlegeId(Long.parseLong(xmlBean.getId()));
            sUserToKnowledge.setUserId(Long.parseLong(userId));
            SUserToKnowledge sUserToKnowledge1 = sUserToKnowledgeMapper.select(sUserToKnowledge);
            if (sUserToKnowledge1 == null) {
                sKnowledge.setIsCollection(0);
                sKnowledge.setIsStudy(0);
            } else {
                sKnowledge.setIsCollection(sUserToKnowledge1.getIsCollection());
                sKnowledge.setIsStudy(sUserToKnowledge1.getIsStudy());
            }
        }

        //知识点标签
        List<String> strings = sKnowledgeLabelMapper.selectLabel(sKnowledge.getId());
        sKnowledge.setLabelList(strings);

        //评论
        List<SKnowledgeDiscuss> sKnowledgeDiscusses = sKnowledgeDiscussMapper.selectDischssByKnowledgeId(xmlBean.getId());
        Page<SKnowledgeDiscuss> page = new Page<>();
        page.setP(xmlBean.getP()==null? 1:Integer.parseInt(xmlBean.getP()));
        List<SKnowledgeDiscuss> list = page.getPageContent(sKnowledgeDiscusses);

        Map<String,Object> map = new HashMap<>();
        map.put("detail",sKnowledge);
        map.put("list",list);
        map.put("count",page.getPageTotal());
        map.put("total",page.getRecordTotal());

        return ObjectResult.build("1","成功",map);
    }

    @Override
    public ObjectResult relatedVideos(XMLBean xmlBean) {

        String userId = CommonUtils.decToken(xmlBean.getToken());

        SKnowledge sKnowledge = sKnowledgeMapper.selectByPrimaryKey(Integer.parseInt(xmlBean.getId()));

        Map<String,Object> map = new HashMap<>();
        map.put("subjectId",sKnowledge.getSubjectId());
        map.put("id",xmlBean.getId());
        List<SKnowledge> list = sKnowledgeMapper.selectKnowledgeListBySubjectMap(map);
        Page<SKnowledge> page = new Page<>();
        page.setP(xmlBean.getP()==null? 1:Integer.parseInt(xmlBean.getP()));
        List<SKnowledge> content = page.getPageContent(list);

        for (SKnowledge sKnowledge1:content){
            sKnowledge1.setImage(ConfigUtils.ADMIN_URL+sKnowledge.getImage());

            //知识点标签
            List<String> strings = sKnowledgeLabelMapper.selectLabel(sKnowledge.getId());
            sKnowledge1.setLabelList(strings);

            //是否收藏
            SUserToKnowledge sUserToKnowledge = new SUserToKnowledge();
            sUserToKnowledge.setKonwlegeId(Long.parseLong(sKnowledge.getId()+""));
            sUserToKnowledge.setUserId(Long.parseLong(userId));

            SUserToKnowledge select = sUserToKnowledgeMapper.select(sUserToKnowledge);
            if (select==null){
                sKnowledge1.setIsCollection(0);
            }
            else {
                sKnowledge1.setIsCollection(select.getIsCollection());
            }
        }

        map.clear();
        map.put("count",page.getPageTotal());
        map.put("total",page.getRecordTotal());
        map.put("list",content);

        return ObjectResult.build("1","成功",map);
    }

    @Override
    public ObjectResult publishDiscuss(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());
        try {
            SKnowledgeDiscuss sKnowledgeDiscuss = new SKnowledgeDiscuss();
            sKnowledgeDiscuss.setUserId(Long.parseLong(userId));
            sKnowledgeDiscuss.setContent(xmlBean.getContent());
            sKnowledgeDiscuss.setKnowledgeId(Integer.parseInt(xmlBean.getId()));
            sKnowledgeDiscuss.setAddTime(new Date());
            sKnowledgeDiscuss.setModifyTime(new Date());
            sKnowledgeDiscussMapper.insertSelective(sKnowledgeDiscuss);
        }catch (RuntimeException e){
            ExceptionUtil.logError(e,log);
            return ObjectResult.build("0","评论失败");
        }
        return ObjectResult.build("1","评论成功");
    }

    @Override
    public ObjectResult addCollection(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());

        SKnowledge sKnowledge = sKnowledgeMapper.selectByPrimaryKey(Integer.parseInt(xmlBean.getId()));
        if(sKnowledge==null){
            return ObjectResult.build("0","未找到该知识点");
        }

        SUserToKnowledge sUserToKnowledge = new SUserToKnowledge();
        sUserToKnowledge.setKonwlegeId(Long.parseLong(xmlBean.getId()));
        sUserToKnowledge.setUserId(Long.parseLong(userId));
        SUserToKnowledge sUserToKnowledge1 = sUserToKnowledgeMapper.select(sUserToKnowledge);
        try {
            //没有就添加，有则修改
            if (sUserToKnowledge1 == null){
                sUserToKnowledge.setIsCollection(1);
                sUserToKnowledge.setAddTime(new Date());
                sUserToKnowledge.setModifyTime(new Date());
                sUserToKnowledgeMapper.insertSelective(sUserToKnowledge);
            }else {
                sUserToKnowledge.setIsCollection(sUserToKnowledge1.getIsCollection()==0 ? 1:0);
                sUserToKnowledge.setModifyTime(new Date());
                sUserToKnowledgeMapper.update(sUserToKnowledge);
            }

        }catch (RuntimeException e){
            ExceptionUtil.logError(e,log);
            return ObjectResult.build("0","添加或取消收藏失败");
        }
        return ObjectResult.build("1","操作成功");
    }

    @Override
    public ObjectResult subject(XMLBean xmlBean) {
        if ("1".equals(xmlBean.getType())){
            LinkedList<SGrade> list = sGradeMapper.selectGrade();
            for (SGrade sGrade:list){
                sGrade.setTitle(sGrade.getGrade());
            }
            SGrade sGrade = new SGrade();
            sGrade.setId(0);
            sGrade.setTitle("全部");
            sGrade.setGrade("全部");
            list.addFirst(sGrade);
            return ObjectResult.build("1","成功",list);
        }
        if ("2".equals(xmlBean.getType())){
            LinkedList<SSubject> list = sSubjectMapper.selectSubjectAll();
            SSubject sSubject = new SSubject();
            sSubject.setTitle("全部");
            list.addFirst(sSubject);
            return ObjectResult.build("1","成功",list);
        }
        return null;
    }

    @Override
    public ObjectResult knowledgePay(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());

        SKnowledge sKnowledge = sKnowledgeMapper.selectByPrimaryKey(Integer.parseInt(xmlBean.getId()));
        if(sKnowledge==null){
            return ObjectResult.build("0","未找到该知识点");
        }

        if(sKnowledge.getPrice().compareTo(new BigDecimal(0))==0){
            return ObjectResult.build("0","免费的知识点无须购买");
        }

        SKnowledgePay sKnowledgePay = new SKnowledgePay();
        sKnowledgePay.setUserId(Long.parseLong(userId));
        sKnowledgePay.setKnowledgeId(sKnowledge.getId());

        SKnowledgePay sKnowledgePay1 = sKnowledgePayMapper.selectKnowledgePay(sKnowledgePay);

        if(sKnowledgePay1 != null && 1== sKnowledgePay1.getIsPay()){
             ObjectResult.build("1","您已购买");
         }

         try {
             String rechargeNo = CommonUtils.getRechargeNo("10002");

             if(sKnowledgePay1 != null && 0== sKnowledgePay1.getIsPay()){
                 sKnowledgePay1.setOrderNo(rechargeNo);
                 sKnowledgePayMapper.updateByPrimaryKeySelective(sKnowledgePay1);
             }else {
                 sKnowledgePay.setIsPay(0);
                 sKnowledgePay.setValue(sKnowledge.getPrice());
                 sKnowledgePay.setAddTime(new Date());
                 sKnowledgePay.setModifyTime(new Date());
                 sKnowledgePay.setOrderNo(rechargeNo);
                 sKnowledgePayMapper.insertSelective(sKnowledgePay);
             }

             //实例化客户端
             AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", ALIPAY_APPID
                     , FileUtil.fileRead(ALIPAY_PRIVWER_KEY), "json", "utf-8", FileUtil.fileRead(ALIPAY_PUBLIC_KEY), "RSA2");
             //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
             AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
             //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
             AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
             model.setBody("");
             model.setSubject("错题狗-知识课堂购买");
             model.setOutTradeNo(rechargeNo);
             model.setTimeoutExpress("30m");
             model.setTotalAmount(sKnowledge.getPrice().toString());
             model.setProductCode("QUICK_MSECURITY_PAY");
             request.setBizModel(model);
             request.setNotifyUrl(ConfigUtils.SYS_URL+"knowledge/payNotify");
             try {
                 //这里和普通的接口调用不同，使用的是sdkExecute
                 AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
                 System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
                 return ObjectResult.build("1","创建订单成功",response.getBody());
             } catch (AlipayApiException e) {
                 e.printStackTrace();
             }
         }catch (RuntimeException e){
             ExceptionUtil.logError(e,log);
             return ObjectResult.build("0","购买失败");
         }

        return null;
    }

    @Override
    public ObjectResult knowledgeWeixin(XMLBean xmlBean, String ip) {
        String userId = CommonUtils.decToken(xmlBean.getToken());

        SKnowledge sKnowledge = sKnowledgeMapper.selectByPrimaryKey(Integer.parseInt(xmlBean.getId()));
        if(sKnowledge==null){
            return ObjectResult.build("0","未找到该知识点");
        }

        if(sKnowledge.getPrice().compareTo(new BigDecimal(0))==0){
            return ObjectResult.build("0","免费的知识点无须购买");
        }

        SKnowledgePay sKnowledgePay = new SKnowledgePay();
        sKnowledgePay.setUserId(Long.parseLong(userId));
        sKnowledgePay.setKnowledgeId(sKnowledge.getId());

        SKnowledgePay sKnowledgePay1 = sKnowledgePayMapper.selectKnowledgePay(sKnowledgePay);

        if(sKnowledgePay1 != null && 1== sKnowledgePay1.getIsPay()){
            ObjectResult.build("1","您已购买");
        }


        // 1.微信支付参数
        //微信开放平台审核通过的应用APPID
        String appid = PayConfig.WEIXIN_APPID;
        //微信支付分配的商户号
        String mch_id = PayConfig.MCH_ID;
        //通知地址
        String notify_url = ConfigUtils.SYS_URL+"knowledge/weixinNotify";
        //key为商户平台设置的密钥key
        String appKey = PayConfig.APP_KEY;

        String partnerid = PayConfig.MCH_ID;

        String nonce_str = CommonUtils.getRandomString(12);
        WeixinPayParam wxpp = new WeixinPayParam();
        Map<String, String> params = new HashMap<String, String>();
        params.put("appid", appid);
        params.put("mch_id", mch_id);
        try {
            //生成订单号
            String rechargeNo = CommonUtils.getRechargeNo("10002");

            if(sKnowledgePay1 != null && 0== sKnowledgePay1.getIsPay()){
                sKnowledgePay1.setOrderNo(rechargeNo);
                sKnowledgePayMapper.updateByPrimaryKeySelective(sKnowledgePay1);
            }else {
                sKnowledgePay.setIsPay(0);
                sKnowledgePay.setValue(sKnowledge.getPrice());
                sKnowledgePay.setAddTime(new Date());
                sKnowledgePay.setModifyTime(new Date());
                sKnowledgePay.setOrderNo(rechargeNo);
                sKnowledgePayMapper.insertSelective(sKnowledgePay);
            }

            params.put("body", "cuotigou");
            params.put("out_trade_no", rechargeNo);

            String strAmt = sKnowledge.getPrice().multiply(new BigDecimal(100)).setScale(0).toString();

            params.put("total_fee", strAmt);
            params.put("spbill_create_ip", ip);
            params.put("trade_type", "APP");
            params.put("nonce_str", nonce_str);
            params.put("notify_url", notify_url);

            String sign = PaymentKit.createSign(params, appKey);
            params.put("sign", sign);

            String xml = PaymentKit.toXml(params);

            log.info("请求参数:" + xml);
            String returnXml = null;
            try {
                returnXml = HttpUtils.executePostMethod(
                        "https://api.mch.weixin.qq.com/pay/unifiedorder",
                        "UTF-8", xml);
            } catch (IOException e) {
                e.printStackTrace();
            }
            log.info("返回结果:" + returnXml);
            ParamsUtil paramsUtil = new ParamsUtil();
            String retCode = paramsUtil.getValue("result_code",
                    returnXml);
            String returnCode = paramsUtil.getValue("return_code",
                    returnXml);// return_code
            if (StringUtils.contains(returnCode, "FAIL")) {

                return ObjectResult.build("0","使用微信下单失败");

            }
            if (StringUtils.contains(retCode, "SUCCESS")) {
                String payIdStr = paramsUtil.getValue("prepay_id",
                        returnXml);
                String payId = payIdStr.substring(9, 45);
                String signC = "";

                Map<String, String> payParams = new HashMap<String, String>();
                payParams.put("prepayid", payId);
                wxpp.setPrepayId(payId);
                payParams.put("package", "Sign=WXPay");
                wxpp.setWepackage("Sign=WXPay");
                String nonce_strB = CommonUtils.getRandomString(12);
                wxpp.setNonceStr(nonce_strB);
                payParams.put("noncestr", nonce_strB);
                String timeStamp = Long.toString(System
                        .currentTimeMillis() / 1000);
                wxpp.setTimeStamp(timeStamp);
                payParams.put("timestamp", timeStamp);
                wxpp.setAppId(appid);
                payParams.put("appid", appid);
                payParams.put("partnerid", partnerid);
                signC = PaymentKit.createSign(payParams, appKey);
                wxpp.setPaySign(signC);
                wxpp.setPartnerId(partnerid);
                // 2.订单相关参数
                wxpp.setOrderNo(rechargeNo);
                wxpp.setGoodTitle("错题狗-会员充值");
                wxpp.setAllOrderAmount(sKnowledge.getPrice());
            } else {
                return ObjectResult.build("0","使用微信下单失败");
            }
        } catch (RuntimeException e) {
            ExceptionUtil.logError(e,log);
            return ObjectResult.build("0","创建订单失败");
        }

        return ObjectResult.build("1","成功",wxpp);
    }

    @Override
    public void payNotify(Map<String, String> map) {
        String out_trade_no = map.get("out_trade_no");
        SKnowledgePay sKnowledgePay = sKnowledgePayMapper.selectByOrderNo(out_trade_no);
        if (sKnowledgePay == null){
            log.info("---------------订单错误-----------------");
            return;
        }

        sKnowledgePay.setIsPay(1);
        sKnowledgePayMapper.updateByPrimaryKeySelective(sKnowledgePay);

        log.info("---------------支付成功-----------------");
    }

    @Override
    public ObjectResult applePay(String userId, String id) {
        SKnowledge sKnowledge = sKnowledgeMapper.selectByPrimaryKey(Integer.parseInt(id));
        if(sKnowledge==null){
            return ObjectResult.build("0","未找到该知识点");
        }

        if(sKnowledge.getPrice().compareTo(new BigDecimal(0))==0){
            return ObjectResult.build("0","免费的知识点无须购买");
        }

        String rechargeNo = CommonUtils.getRechargeNo("10002");

        SKnowledgePay sKnowledgePay = new SKnowledgePay();
        sKnowledgePay.setUserId(Long.parseLong(userId));
        sKnowledgePay.setKnowledgeId(sKnowledge.getId());
        sKnowledgePay.setIsPay(1);
        sKnowledgePay.setValue(sKnowledge.getPrice());
        sKnowledgePay.setAddTime(new Date());
        sKnowledgePay.setModifyTime(new Date());
        sKnowledgePay.setOrderNo(rechargeNo);
        sKnowledgePayMapper.insertSelective(sKnowledgePay);

        return ObjectResult.build("1","购买成功");

    }

    @Override
    public ObjectResult knowledgeStudy(XMLBean xmlBean) {
        SKnowledge sKnowledge = sKnowledgeMapper.selectByPrimaryKey(Integer.parseInt(xmlBean.getId()));
        if (sKnowledge == null){
            return ObjectResult.build("0","视频播放错误");
        }

//        SUserToKnowledge sUserToKnowledge = new SUserToKnowledge();
//        sUserToKnowledge.setUserId(Long.parseLong(userId));
//        sUserToKnowledge.setKonwlegeId(Long.parseLong(xmlBean.getId()));
//        SUserToKnowledge select = sUserToKnowledgeMapper.select(sUserToKnowledge);

//        if (select == null){
//            sUserToKnowledge.setIsStudy(1);
//            sUserToKnowledge.setAddTime(new Date());
//            sUserToKnowledge.setModifyTime(new Date());
//            sUserToKnowledgeMapper.insertSelective(sUserToKnowledge);
//
//            sKnowledge.setCount(sKnowledge.getCount()+1);
//            sKnowledgeMapper.updateByPrimaryKeySelective(sKnowledge);
//        }else if (select.getIsStudy()!=1){
//            sUserToKnowledge.setIsStudy(1);
//            sUserToKnowledge.setModifyTime(new Date());
//            sUserToKnowledgeMapper.update(sUserToKnowledge);

            sKnowledge.setCount(sKnowledge.getCount()+1);
            sKnowledgeMapper.updateByPrimaryKeySelective(sKnowledge);
//        }
        return ObjectResult.build("1","成功");
    }
}